package com.lzh.fastjson.serializer;

import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.ObjectSerializer;

import java.io.IOException;
import java.lang.reflect.Type;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;

/**
 * @author zhehen.lu
 * @date 2025/8/10 14:41
 */
public class FastjsonYearMonthSerializer implements ObjectSerializer {
    private static String PATTERN = "yyyy-MM";

    public FastjsonYearMonthSerializer() {
    }

    @Override
    public void write(JSONSerializer jsonSerializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
        if (object == null) {
            jsonSerializer.getWriter().writeNull();
        } else if (!(object instanceof YearMonth)) {
            jsonSerializer.write(object);
        } else {
            YearMonth yearMonth = (YearMonth)object;
            jsonSerializer.out.writeString(yearMonth.format(DateTimeFormatter.ofPattern(PATTERN)));
        }
    }
}